/*
 * svpwm.h
 *
 *  Created on: 2024年11月5日
 *      Author: zizhong
 */

#ifndef CONTROLLIB_SVPWM_H_
#define CONTROLLIB_SVPWM_H_

typedef struct  {
    float  Ualpha;          // Input: reference alpha-axis phase voltage
    float  Ubeta;           // Input: reference beta-axis phase voltage
    float  Ta;              // Output: reference phase-a switching function
    float  Tb;              // Output: reference phase-b switching function
    float  Tc;              // Output: reference phase-c switching function
    float  tmp1;            // Variable: temp variable
    float  tmp2;            // Variable: temp variable
    float  tmp3;            // Variable: temp variable
    uint16_t VecSector;         // Space vector sector
}SVM_ctl_t;

#define SVGEN_DEFAULTS { 0,0,0,0,0 }

static inline void runSVGenDQ(SVM_ctl_t * in)
{
    in->tmp1 = in->Ubeta;
    in->tmp2 = (in->Ubeta / 2) + (0.866 * in->Ualpha);
    in->tmp3 = in->tmp2 - in->tmp1;

    in->VecSector = 3;
    in->VecSector = (in->tmp2 > 0)?(in->VecSector - 1):in->VecSector;
    in->VecSector = (in->tmp3 > 0)?(in->VecSector - 1):in->VecSector;
    in->VecSector = (in->tmp1 < 0)?(7 - in->VecSector):in->VecSector;

    if(in->VecSector == 1 || in->VecSector == 4)
    {
        in->Ta = in->tmp2;
        in->Tb = in->tmp1 - in->tmp3;
        in->Tc = -in->tmp2;
    }
    else if(in->VecSector == 2 || in->VecSector == 5)
    {
        in->Ta = in->tmp3 + in->tmp2;
        in->Tb = in->tmp1;
        in->Tc = -in->tmp1;
    }
    else
    {
        in->Ta = in->tmp3;
        in->Tb = -in->tmp3;
        in->Tc = -(in->tmp1 + in->tmp2);
    }
}

#endif /* CONTROLLIB_SVPWM_H_ */
